<?php

/**
 * @return string
 */
function base_path(): string
{
    return APPLICATION_PATH;
}

/**
 * @return string
 */
function app_path(): string
{
    return __DIR__;
}

/**
 * @return string
 */
function config_path(): string
{
    return APPLICATION_PATH . DIRECTORY_SEPARATOR . 'conf';
}

/**
 * @return string
 */
function public_path(): string
{
    return APPLICATION_PATH . DIRECTORY_SEPARATOR . 'public';
}

/**
 * @return string
 */
function runtime_path(): string
{
    return APPLICATION_PATH . DIRECTORY_SEPARATOR . 'runtime';
}

/**
 * 调试函数(FPM使用)
 * @param $data
 */
function p_pre($data)
{
    $str = '<pre style="display: block;padding: 5px;margin: 2px 0 20px 0;font-size: 13px;line-height: 1.5;color: #333;word-break: break-all;word-wrap: break-word;background-color: #F5F5F5;border: 1px solid #CCC;border-radius: 4px;">';
    switch (true) {
        case is_bool($data):
            $show_data = $data ? 'true' : 'false';
            break;
        case is_null($data):
            $show_data = 'null';
            break;
        default:
            $show_data = print_r($data, true);
            break;
    }
    $str .= $show_data;
    $str .= '</pre>';
    echo $str;
}

/**
 * 调试函数(CLI使用)
 * @param mixed $data
 * @param bool $echo
 * @return string
 */
function p($data, bool $echo = false): string
{
    $hr = PHP_EOL.'******************************'.\date('Y-m-d H:i:s').PHP_EOL;
    $str = $hr;
    switch (true) {
        case is_bool($data):
            $show_data = $data ? 'true' : 'false';
            break;
        case is_null($data):
            $show_data = 'null';
            break;
        default:
            $show_data = print_r($data, true);
            break;
    }
    $str .= $show_data;
    $str .= $hr;
    if ($echo) {
        echo $str;
    }
    return $str;
}

/**
 * 文件调试
 * @param mixed $data
 * @param string|int $line
 * @return void
 */
function file_debug($data, $line = 0)
{
    file_put_contents(runtime_path() . DIRECTORY_SEPARATOR . '/file_debug_' . $line . '.log', p($data, false));
}

/**
 * Curl发送请求
 * @param string $url       链接
 * @param array $fields     参数
 * @param bool $isGet      请求类型
 * @param string $cookies   Cookie
 * @return array
 */
function curl_http_request(string $url, array $fields = array(), bool $isGet = true, string $cookies = ''):array
{
    $UserAgent ='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36';
    $headers = [
        'Accept-Language' => 'Accept-Language: zh-CN,zh;q=0.9',
        'Content-Type'    => 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'
    ];

    $cl = curl_init();
    if ($isGet) {
        // GET请求
        curl_setopt($cl, CURLOPT_HTTPGET, true);
        if (!empty($fields)) {
            $url = $url . (strpos($url, '?') === false ? '?' : '&') . http_build_query($fields);
        }
    } else {
        // POST请求
        curl_setopt($cl, CURLOPT_POST, true);
        if (!empty($fields)) {
            if (is_array($fields) || is_object($fields)) {
                $skip = false;
                foreach ($fields as $key => $value) {
                    // POST文件时（instanceof \CurlFile），跳过http_build_query
                    if ($value instanceof \CurlFile) {
                        $skip = true;
                    }
                }
                if (!$skip) {
                    $fields = http_build_query($fields);
                }
            }
            curl_setopt($cl, CURLOPT_POSTFIELDS, $fields);
        }
    }

    curl_setopt($cl, CURLOPT_URL, $url);
    if (stripos($url, 'https://') === 0) {
        curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false);
        //curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, 2);    // 可注释，可选值0,2
        //curl_setopt($cl, CURLOPT_SSLVERSION, 1);        // 可注释
    }
    curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($cl, CURLOPT_USERAGENT, $UserAgent);
    curl_setopt($cl, CURLOPT_HTTPHEADER, array_values($headers));
    if (!empty($cookies)) {
        curl_setopt($cl, CURLOPT_COOKIE, $cookies);
    }
    curl_setopt($cl, CURLOPT_CONNECTTIMEOUT, 3);
    curl_setopt($cl, CURLOPT_TIMEOUT, 6);
    // 结果
    $ret = [
        'response'  =>  curl_exec($cl),
        'status'    =>  curl_getinfo($cl)
    ];
    // 关闭curl
    is_resource($cl) and curl_close($cl);

    return $ret;
}

/**
 * 获取当前版本时间
 * @param string $branch
 * @return string
 */
function get_current_git_fileMtime(string $branch = 'master'):string
{
    if ($time = filemtime(sprintf(base_path() . '/.git/refs/heads/%s', $branch))) {
        return date("Y-m-d H:i:s", $time);
    }
    return 'NaN';
}

/**
 * 获取当前版本commit
 * @param string $branch
 * @param bool $short
 * @return string
 */
function get_current_git_commit(string $branch = 'master', bool $short = true):string
{
    if ($hash = file_get_contents(sprintf(base_path() . '/.git/refs/heads/%s', $branch))) {
        $hash = trim($hash);
        return $short ? substr($hash, 0, 7) : $hash;
    }
    return '';
}

/**
 * 清空目录下的所有文件
 * @param string $path   需要删除目录路径
 * @return bool         false:失败; true:成功;
 */
function clearDir(string $path):bool
{
    if ($path[0] != '.' && is_dir($path) && is_writable($path)) {
        $dirRes = opendir($path);
        while (false !== ($fileName = readdir($dirRes))) {
            if (($fileName != '.') && ($fileName != '..')) {
                $fullPath = $path.'/'.$fileName;
                if (is_file($fullPath)) {
                    unlink($fullPath);
                } else {
                    clearDir($fullPath);
                    rmdir($fullPath);
                }
            }
        }
        closedir($dirRes);
        return true;
    } else {
        return false;
    }
}

/**
 * 判断URL是否编码
 * @param $string
 * @return bool
 */
function isUrlEncoded($string):bool
{
    $test_string = $string;
    while (urldecode($test_string) != $test_string) {
        $test_string = urldecode($test_string);
    }
    return (urlencode($test_string) === $string);
}
